package com.hxy.shiro;
import com.hxy.pojo.UserInf;
import com.hxy.pojo.Userpope;
import com.hxy.service.UserInfService;
import com.hxy.service.UserpopeService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;

/**
 * 自定义Realm  获取用户登录和权限信息
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserInfService userInfService;
    @Autowired
    private UserpopeService UserpopeService;
    /**
     * 获取用户权限信息
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户名
        String username = (String) principalCollection.getPrimaryPrincipal();
        //创建SimpleAuthenticationInfo对象
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //根据用户名获取权限信息
        UserInf userInf=userInfService.findByUsername(username);
        //获取权限名字
        List<String> permissionNames = UserpopeService.findPopeNameByUserID(userInf.getStatusId());
        //如果用户是root,要处理root的权限
        if (userInf.getStatusId()==3){
            //root用户
            //查询所有权限信息
            List<Userpope> permissions = UserpopeService.selectAll();
            //遍历权限信息集合,把权限的名称添加到permissionNmaes中
            for (Userpope permission : permissions) {
                permissionNames.add(permission.getPopename());
            }
        }
        //SimpleAuthenticationInfo对象设置权限,角色字符串信息
        authorizationInfo.setStringPermissions(new HashSet<>(permissionNames));
        //返回SimpleAuthenticationInfo对象
        return authorizationInfo;
    }

    /**
     * 获取登录认证信息
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.获取用户名

        String username = (String) authenticationToken.getPrincipal();
        //2.根据用户名查询用户信息

        UserInf admin = userInfService.findByUsername(username);
        //3.判断用户信息 是否为空,抛出异常
        if (admin == null) {
            throw new UnknownAccountException();//没找到帐号
        }
        //3.用户信息不为空  创建SimpleAuthenticationInfo对象，三个参数，正确用户名、正确的密码、realmName*
        //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以自定义实现
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                admin.getUsername(), //用户名
                admin.getPassword(),

                getName()  //realm name
        );


        return authenticationInfo;
    }
}